package org.apache.curator;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.framework.recipes.cache.NodeCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.test.TestingServer;
import org.apache.zookeeper.CreateMode;

public class NodeCacheDemo {
    public static void main(String[]args) throws Exception{
        TestingServer server=null;
        CuratorFramework client=null;
        NodeCache nodeCache=null;
        String path="/dlh";


        try{
            server=new TestingServer();
            client= CuratorFrameworkFactory.newClient("192.168.220.146:2181", new ExponentialBackoffRetry(1000,3));
            client.start();

            path=client.create().creatingParentsIfNeeded().withProtection().withMode(CreateMode.EPHEMERAL).forPath(path,"init".getBytes());


            nodeCache=new NodeCache(client,path,false);
            nodeCache.start();
            addListener(nodeCache);



            client.setData().forPath(path,"hello".getBytes());
            Thread.sleep(1000);
            //client.delete().deletingChildrenIfNeeded().forPath(path);
            Thread.sleep(Integer.MAX_VALUE);

        }catch(Exception e){
            e.printStackTrace();
        }finally{


            //这里因为是测试，没有加他们。
            //CloseableUtils.closeQuietly(nodeCache);
            /// CloseableUtils.closeQuietly(client);
            // CloseableUtils.closeQuietly(server);
        }
    }

    public static void addListener(NodeCache nodeCache){
        //监听类型：节点是否存在，节点数据内容改变，不监听节点删除。
        nodeCache.getListenable().addListener(new NodeCacheListener(){

            @Override
            public void nodeChanged() throws Exception {
                // TODO Auto-generated method stub
                if(nodeCache.getCurrentData()!=null)
                    System.out.println("path:"+nodeCache.getCurrentData().getPath()+",data:"+new String(nodeCache.getCurrentData().getData()));

            }});
    }
}